package com.example.javachatroomextend.controller;

import com.example.javachatroomextend.model.Result;
import com.example.javachatroomextend.model.Session;
import com.example.javachatroomextend.model.User;
import com.example.javachatroomextend.service.FriendService;
import com.example.javachatroomextend.service.NewFriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/friend")
public class FriendController {
    @Autowired
    private FriendService friendService;

    @Autowired
    private NewFriendService newFriendService;

    @GetMapping("/getFriendList")
    public Result<List<Session>> getFriendList(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        List<Session> ret = friendService.getFriendList(user.getUserId());
        ret.sort(Comparator.comparing(Session::getFriendName));
        return Result.success(ret);
    }

    @PostMapping("/addFriend")
    public Result<Boolean> addFriend(Integer userId,Integer friendId) {
        Integer ret = friendService.addFriend(userId,friendId);
        if (ret == null) {
            return Result.fail(500,false,"服务器内部出现错误，请联系管理员");
        }
        ret = friendService.addFriend(friendId,userId);
        newFriendService.delete(userId,friendId);
        newFriendService.delete(friendId,userId);
        if (ret == null) {
            return Result.fail(500,false,"服务器内部出现错误，请联系管理员");
        }
        return Result.success(true);
    }
}
